<?php
require_once ("app/model/User.php");
require_once ("app/model/Team.php");
require_once ("app/model/Role.php");
require_once ("app/lib/Pager.php");

class WizardController extends Zend_Controller_Action {
	private $user;
	private $team;
	private $role;

	function preDispatch() {
		$this->view->user = Zend_Auth::getInstance()->getIdentity();
		$this->view->controller = $this->_request->getControllerName();
		$this->view->action = $this->_request->getActionName();
		$subMenu = array (
			'Main' => array (
				'key' => 'index',
				'url' => '/wizard/',
				'selected' => false,
				'title' => 'wizard introduction page',
			),
			'User' => array (
				'key' => 'user',
				'url' => '/wizard/user',
				'selected' => false,
				'title' => 'wizard to maintain user',
			),
			'Team' => array (
				'key' => 'team',
				'url' => '/wizard/team',
				'selected' => false,
				'title' => 'wizard to maintain team'
			),
			'Role' => array (
				'key' => 'role',
				'url' => '/wizard/role',
				'selected' => false,
				'title' => 'wizard to maintain role'
			),
			'Task' => array (
				'key' => 'task',
				'url' => '/wizard/task',
				'selected' => false,
				'title' => 'wizard to maintain task'
			),
			'Score' => array (
				'key' => 'score',
				'url' => '/wizard/score',
				'selected' => false,
				'title' => 'wizard to maintain score'
			)
		);
		$menu = new Menu();
		$menuTree = $menu->renderMenu($this->_request->getControllerName(), $this->_request->getActionName(), $subMenu);
		$this->view->menuTree = $menuTree;

		$this->user = new User();
		$this->team = new Team();
		$this->role = new Role();
	}

	function indexAction() {

	}

	/*
	 * User listing, add new user, delete user
	 */
	function userAction() {
		$errorMsgs = array ();
		//$this->view->post = $_POST;

		/*add user process*/
		if ($this->_getParam('act') == 'add') {
			if (trim($_POST['name']) == "") {
				$errorMsgs[] = "Please set a name for the new user.";
			}

			if (count($errorMsgs) < 1 && trim($_POST['passwd']) == "") {
				$errorMsgs[] = "Please set a password for " . $_POST['name'] . ".";
			}

			if (count($errorMsgs) < 1) {
				$where = "name like '%" . trim($_POST['name']) . "%'";
				$selUsers = $this->user->findUser($where);
				if (count($selUsers) > 0) {
					$errorMsgs[] = "User " . $_POST['name'] . " has existed in the table.";
				}
				if (count($errorMsgs) < 1) {
					$newUser = array (
						'name' => trim($_POST['name']
					), 'passwd' => trim($_POST['passwd']), 'email' => trim($_POST['email']), 'phone' => trim($_POST['phone']), 'tt_role_id' => trim($_POST['role']), 'tt_team_id' => trim($_POST['team']));
					$this->user->insert($newUser);
					$this->view->displayErrorTitle = false;
					$errorMsgs[] = $newUser['name'] . " has been successfully added into the user table!";
				}
			}
		}

		/*User delete process*/
		if ($this->_getParam('act') == 'del') {
			$where = $this->user->getAdapter()->quoteInto('id = ?', $_POST['userid']);
			$this->user->delete($where);
		}
		$this->view->errors = $errorMsgs;

		//select user out, todo: cache the result
		$curPage = $this->_getParam('p');
		if ($curPage < 1) {
			$curPage = 1;
		}
		$perPage = 20;
		$wUserNamespace = new Zend_Session_Namespace('Zend_Wizard_User');
		$where = array (
			"name" => (isset ($_REQUEST['qName']
		)) ? trim($_REQUEST['qName']) : $wUserNamespace->pagingParams['name'], "tt_team_id" => isset ($_REQUEST['qTeam']) ? $_REQUEST['qTeam'] : $wUserNamespace->pagingParams['tt_team_id'], "tt_role_id" => isset ($_REQUEST['qRole']) ? $_REQUEST['qRole'] : $wUserNamespace->pagingParams['tt_role_id']);
		//$order = "t.id, r.id";
		$order = "u.id";
		$wUserNamespace->pagingParams = $where;
		$this->view->pagingParams = $where;

		$this->view->userList = $this->user->getFullUserList($where, $order, ($curPage -1) * $perPage, $perPage);
		//paging
		$pagingSetting = array (
			'Mode' => 2,
			'Paging' => $this->getRequest()->getBaseUrl() . '/wizard/user/p/{page}',
			'Prev' => '<',
			'Next' => '>'
		);
		$paging = new Pager($perPage, $curPage, $this->user->_totalCount, $pagingSetting);
		$pager = $paging->toArray();
		$this->view->pager = ($pager['totalPage'] > 1) ? $pager : null;

		$team = new Team();
		$where = array (
			'flag = ?' => 1
		);
		$order = "name";
		$teams = $team->fetchAll($where, $order);
		$this->view->teamList = $teams;

		$role = new Role();
		$this->view->roleList = $role->fetchAll($where, $order);
		$this->view->userTeamList = $this->user->getUserTeams();
		$this->view->userRoleList = $this->user->getUserRoles();
	}

	/*
	 * User info update
	 */
	function usereditAction() {
		$userId = $_REQUEST['userid'];

		if ($_POST['act'] == 'edit') {
			if (trim($_POST['name']) == "") {
				$errorMsgs[] = "Name is required.";
			}

			if (count($errorMsgs) < 1 && trim($_POST['passwd']) == "") {
				$errorMsgs[] = "Password is required.";
			}

			if (count($errorMsgs) < 1) {
				$where = " u.id <>" . $userId . " and name like '" . trim($_POST['name']) . "'";
				$selUsers = $this->user->findUser($where);
				if (count($selUsers) > 0) {
					$errorMsgs[] = "Name: " . $_POST['name'] . " has been used by other people.";
				}
				if (count($errorMsgs) < 1) {
					$userInfo = array (
						'name' => trim($_POST['name']
					), 'passwd' => trim($_POST['passwd']), 'email' => trim($_POST['email']), 'phone' => trim($_POST['phone']), 'tt_role_id' => trim($_POST['role']), 'tt_team_id' => trim($_POST['team']));
					$where = $this->user->getAdapter()->quoteInto('id = ?', $userId);
					$this->user->update($userInfo, $where);
					$this->view->displayErrorTitle = false;
					$errorMsgs[] = $userInfo['name'] . " has been updated!";
				}
			}
		}
		$this->view->errors = $errorMsgs;
		$this->view->userInfo = $this->user->getUser($userId);

		$team = new Team();
		$where = array (
			'flag = ?' => 1
		);
		$order = "name";
		$teams = $team->fetchAll($where, $order);
		$this->view->teamList = $teams;

		$role = new Role();
		$this->view->roleList = $role->fetchAll($where, $order);
	}

	/*
	 * team listing, add new team, delete team
	 */
	function teamAction() {
		$errorMsgs = array ();
		//$this->view->post = $_POST;

		/*add team process*/
		if ($this->_getParam('act') == 'add') {
			if (trim($_POST['name']) == "") {
				$errorMsgs[] = "Please set a name for the new team.";
			}

			if (trim($_POST['abs']) == "") {
				$errorMsgs[] = "Please set a abs for the new team.";
			}

			if (count($errorMsgs) < 1) {
				$where = "name like '%" . trim($_POST['name']) . "%'";
				$selTeams = $this->team->findTeam($where);
				if (count($selTeams) > 0) {
					$errorMsgs[] = "Team " . $_POST['name'] . " has existed in the table.";
				}
				if (count($errorMsgs) < 1) {
					$newTeam = array (
						'name' => trim($_POST['name']
					), 'abs' => trim($_POST['abs']));
					$this->team->insert($newTeam);
					$this->view->displayErrorTitle = false;
					$errorMsgs[] = $newTeam['name'] . " has been successfully added into the team table!";
				}
			}
		}

		/*Team delete process*/
		if ($this->_getParam('act') == 'del') {
			$where = $this->team->getAdapter()->quoteInto('id = ?', $_POST['teamid']);
			$this->team->delete($where);
		}
		$this->view->errors = $errorMsgs;

		//select team out, todo: cache the result
		$curPage = $this->_getParam('p');
		if ($curPage < 1) {
			$curPage = 1;
		}
		$perPage = 10;
		$wTeamNamespace = new Zend_Session_Namespace('Zend_Wizard_Team');
		$where = array(
			"name" => (isset($_REQUEST['qName']))?trim($_REQUEST['qName']):$wTeamNamespace->pagingParams['name']		
		);
		//$order = "t.id, r.id";
		$order = "t.id";
		$wTeamNamespace->pagingParams = $where;
		$this->view->pagingParams = $where;

		$this->view->teamList = $this->team->getFullTeamList($where, $order, ($curPage -1) * $perPage, $perPage);
		//paging
		$pagingSetting = array (
			'Mode' => 2,
			'Paging' => '/wizard/team/p/{page}',
			'Prev' => '<',
			'Next' => '>'
		);
		$paging = new Pager($perPage, $curPage, $this->team->_totalCount, $pagingSetting);
		$pager = $paging->toArray();
		$this->view->pager = ($pager['totalPage'] > 1) ? $pager : null;
	}

	/*
	 * team info update
	 */
	function teameditAction() {
		$teamId = $_REQUEST['teamid'];

		if ($_POST['act'] == 'edit') {
			if (trim($_POST['name']) == "") {
				$errorMsgs[] = "Name is required.";
			}

			if (trim($_POST['abs']) == "") {
				$errorMsgs[] = "Abs is required.";
			}

			if (count($errorMsgs) < 1) {
				$where = " t.id <>" . $teamId . " and name like '" . trim($_POST['name']) . "'";
				$selTeams = $this->team->findTeam($where);
				if (count($selTeams) > 0) {
					$errorMsgs[] = "Name: " . $_POST['name'] . " has been used by other people.";
				}
				if (count($errorMsgs) < 1) {
					$teamInfo = array (
						'name' => trim($_POST['name']
					), 'abs' => trim($_POST['abs']));
					$where = $this->team->getAdapter()->quoteInto('id = ?', $teamId);
					$this->team->update($teamInfo, $where);
					$this->view->displayErrorTitle = false;
					$errorMsgs[] = $teamInfo['name'] . " has been updated!";
				}
			}
		}
		$this->view->errors = $errorMsgs;
		$this->view->teamInfo = $this->team->getTeam($teamId);
	}

	/*
	 * role listing, add new role, delete role
	 */
	function roleAction() {
		$errorMsgs = array ();
		//$this->view->post = $_POST;
		
		/*add role process*/
		if ($this->_getParam('act') == 'add') {
			if (trim($_POST['name']) == "") {
				$errorMsgs[] = "Please set a name for the new role.";
			}
			
			if (trim($_POST['description']) == "") {
				$errorMsgs[] = "Please set a description for the new role.";
			}

			if (count($errorMsgs) < 1) {
				$where = "name like '%".trim($_POST['name'])."%'";				
				$selRoles = $this->role->findRole($where);				
				if (count($selRoles) > 0) {
					$errorMsgs[] = "Role " . $_POST['name'] . " has existed in the table.";
				}
				if (count($errorMsgs) < 1) {
					$newRole = array (
						'name' => trim($_POST['name']), 
						'description' => trim($_POST['description'])
					);
					$this->role->insert($newRole);
					$this->view->displayErrorTitle = false;
					$errorMsgs[] = $newRole['name']." has been successfully added into the role table!";
				}
			}
		}
		
		/*Role delete process*/
		if ($this->_getParam('act') == 'del') {			
			$where = $this->role->getAdapter()->quoteInto('id = ?', $_POST['roleid']);						
			$this->role->delete($where);
		}
		$this->view->errors = $errorMsgs;

		//select role out, todo: cache the result
		$curPage = $this->_getParam('p');	
		if($curPage<1){
			$curPage = 1;
		}
		$perPage = 10; 
		$wRoleNamespace = new Zend_Session_Namespace('Zend_Wizard_Role');
		$where = array(
			"name" => (isset($_REQUEST['qName']))?trim($_REQUEST['qName']):$wRoleNamespace->pagingParams['name']			
		);
		//$order = "t.id, r.id";
		$order = "t.id";
		$wRoleNamespace->pagingParams = $where;		
		$this->view->pagingParams = $where;
				
		$this->view->roleList = $this->role->getFullRoleList($where,$order,($curPage -1)*$perPage, $perPage);
		//paging
		$pagingSetting = array('Mode' => 2, 'Paging' => '/wizard/role/p/{page}', 'Prev' => '<', 'Next' => '>');
		$paging = new Pager($perPage, $curPage, $this->role->_totalCount, $pagingSetting);
		$pager = $paging->toArray();		
		$this->view->pager = ($pager['totalPage'] > 1) ? $pager : null;
	}

	/*
	 * role info update
	 */
	function roleeditAction() {		
		$roleId = $_REQUEST['roleid'];
		
		if ($_POST['act'] == 'edit') {
			if (trim($_POST['name']) == "") {
				$errorMsgs[] = "Name is required.";
			}
			
			if (trim($_POST['description']) == "") {
				$errorMsgs[] = "Description is required.";
			}

			if (count($errorMsgs) < 1) {
				$where = " t.id <>".$roleId." and name like '".trim($_POST['name'])."'";				
				$selRoles = $this->role->findRole($where);				
				if (count($selRoles) > 0) {
					$errorMsgs[] = "Name: " . $_POST['name'] . " has been used by other people.";
				}
				if (count($errorMsgs) < 1) {
					$roleInfo = array (
						'name' => trim($_POST['name']), 
						'description' => trim($_POST['description'])
					);
					$where = $this->role->getAdapter()->quoteInto('id = ?', $roleId);
					$this->role->update($roleInfo, $where);
					$this->view->displayErrorTitle = false;
					$errorMsgs[] = $roleInfo['name']." has been updated!";
				}
			}
		}		
		$this->view->errors = $errorMsgs;		
		$this->view->roleInfo = $this->role->getRole($roleId);
	}

	/*Wizard to set up role scores*/
	function scoreAction() {
		$team = new Team();
		$where = array (
			'flag = ?' => 1
		);
		$order = "name";
		$teams = $team->fetchAll($where, $order);
		$this->view->teamList = $teams;

		/*CREATE TABLE `tt_score_base` (                                                                                                                                                                                                                                                                                               
		         `id` int(11) NOT NULL auto_increment,                                                                                                                                                                                                                                                                                      
		         `task_id` int(11) default NULL,                                                                                                                                                                                                                                                                                            
		         `score_time` tinyint(3) unsigned default NULL,                                                                                                                                                                                                                                                                             
		         `score_attitude` tinyint(3) unsigned default NULL,                                                                                                                                                                                                                                                                         
		         `score_quality` tinyint(3) unsigned default NULL,                                                                                                                                                                                                                                                                          
		         PRIMARY KEY  (`id`)                                                                                                                                                                                                                                                                                                        
		       ) ENGINE=MyISAM DEFAULT CHARSET=utf8    
		 * */
		$this->view->errors = array ();
		$wScoreNS = new Zend_Session_Namespace('Wizard_Score');
		if (is_array($wScoreNS->scoreDimension)) {
			$scoreDimension = $wScoreNS->scoreDimension;
		} else {
			$scoreDimension = array (
				'id' => array (
					'int(11)',
					'primary key for scores',
					false
				),
				'task_id' => array (
					'int(11)',
					'task which the scores belong to',
					false
				),
				'score_time' => array (
					'tinyint',
					'time cost',
					true
				),
				'score_attitude' => array (
					'tinyint',
					'the attitude roles involved',
					true
				),
				'score_quality' => array (
					'tinyint',
					'quality of the task',
					true
				)
			);
		}

		if ($this->_getParam('act') == 'new') {
			if ($_POST['team'] == "") {
				$this->view->errors[] = "Please select a team!";
			} else {
				if (array_key_exists(trim($_POST['newFieldName']), $scoreDimension)) {
					$this->view->errors[] = "Dimension has exists!";
				} else {
					$scoreDimension[trim($_POST['newFieldName'])] = array (
						"tinyint",
						trim($_POST['newFieldDesc']
					), true);
					$wScoreNS->scoreDimension = $scoreDimension;
				}
			}
		}
		if ($this->_getParam('act') == 'del') {
			unset ($scoreDimension[trim($_POST['dName'])]);
			$wScoreNS->scoreDimension = $scoreDimension;
		}

		if ($this->_getParam('act') == 'createTable') {
			if ($_POST['team'] == "") {
				$this->view->errors[] = "Please select a team!";
			}
		}
		$sqlDimen = "CREATE TABLE tt_".trim($this->_getParam('team'))."_score(<br>";
		foreach ($scoreDimension as $k => $v) {
			$sqlDimen .= $k . " " . $v[0] . " not null default 0,<br>";
		}
		$sqlDimen .= "PRIMARY KEY id <br>)";
		$this->view->sqlDimen = $sqlDimen;
		$this->view->scoreDimensions = $scoreDimension;
		$this->view->teamId = $this->_getParam('team');
		if(count($this->view->errors)>0){
			$this->view->newFieldName = $_POST['newFieldName'];
			$this->view->newFieldDesc = $_POST['newFieldDesc'];
		}
	}
	
	/*Wizard to set up role tasks*/
	function taskAction() {
		$team = new Team();
		$where = array (
			'flag = ?' => 1
		);
		$order = "name";
		$teams = $team->fetchAll($where, $order);
		$this->view->teamList = $teams;

		/*CREATE TABLE `tt_st_task` (                 
              `id` int(11) NOT NULL auto_increment,     
              `title` varchar(255) NOT NULL,            
              `request_id` int(10) default '0',         
              `manager_id` int(10) default '0',         
              `developer_id` int(10) default '0',       
              `property_id` int(10) default '0',        
              `description` text NOT NULL,              
              `date_start` date default '0000-00-00',   
              `date_end` date default '0000-00-00',     
              `duration` int(10) default '0',           
              `task_status` tinyint(3) default '0',     
              `task_prior` tinyint(3) default '0',      
              `task_type` tinyint(3) default '0',       
              `task_note` text,                         
              `has_attachment` tinyint(1) default '0',  
              `man_hour` tinyint(3) default '0',        
              `weight` tinyint(2) default '0',          
              `sup_task_id` int(11) default '0',        
              PRIMARY KEY  (`id`)                       
            ) ENGINE=InnoDB DEFAULT CHARSET=utf-8    
		 * */
		$this->view->errors = array ();
		$wTaskNS = new Zend_Session_Namespace('Wizard_Task');
		if (is_array($wTaskNS->taskDimension)) {
			$taskDimension = $wTaskNS->taskDimension;
		} else {
			$taskDimension = array (
				'id' => array (
					'int(11)',
					'primary key for tasks',
					false,
					' NOT NULL auto_increment,'
				),
				'title' => array (
					'varchar(255)',
					'',
					true,
					','
				),
				'request_id' => array (
					'int(10)',
					'',
					true,
					' NOT NULL default 0,'
				),
				'manager_id' => array (
					'int(10)',
					'',
					true,
					' NOT NULL default 0,'
				),
				'developer_id' => array (
					'int(10)',
					'',
					true,
					' NOT NULL default 0,'
				),
				'property_id' => array (
					'int(10)',
					'',
					true,
					' NOT NULL default 0,'
				),
				'description' => array (
					'text',
					'',
					true,
					','
				),
				'date_start' => array (
					'date',
					'',
					true,
					' NOT NULL default \'0000-00-00\','
				),
				'date_end' => array (
					'date',
					'',
					true,
					' NOT NULL default \'0000-00-00\','
				),
				'duration' => array (
					'int(10)',
					'',
					true,
					' NOT NULL default 0,'
				),
				'task_status' => array (
					'tinyint(3)',
					'',
					true,
					' NOT NULL default 0,'
				),
				'task_prior' => array (
					'tinyint(3)',
					'',
					true,
					' NOT NULL default 0,'
				),
				'task_type' => array (
					'tinyint(3)',
					'',
					true,
					' NOT NULL default 0,'
				),
				'task_note' => array (
					'text',
					'',
					true,
					','
				),
				'has_attachment' => array (
					'tinyint(1)',
					'',
					true,
					' NOT NULL default 0,'
				),
				'man_hour' => array (
					'tinyint(3)',
					'',
					true,
					' NOT NULL default 0,'
				),
				'weight' => array (
					'tinyint(2)',
					'',
					true,
					' NOT NULL default 0,'
				),
				'sup_task_id' => array (
					'int(11)',
					'',
					true,
					' NOT NULL default 0,'
				)
			);
		}

	if(isset($_POST['act'])){
		if ($_POST['act'] == 'new') {
			if ($_POST['team'] == "") {
				$this->view->errors[] = "Please select a team!";
			} else {
				if (array_key_exists(trim($_POST['newFieldName']), $taskDimension)) {
					$this->view->errors[] = "Dimension has exists!";
				} else {
					$taskDimension[trim($_POST['newFieldName'])] = array (
						$_POST['coltype'],
						trim($_POST['newFieldDesc']
					), true,'');
					$wTaskNS->taskDimension = $taskDimension;
				}
			}
		}
		if ($_POST['act'] == 'del') {
			unset ($taskDimension[trim($_POST['dName'])]);
			$wTaskNS->taskDimension = $taskDimension;
		}

		if ($_POST['act'] == 'createTable') {
			if ($_POST['team'] == "") {
				$this->view->errors[] = "Please select a team!";
			}
		}

	}

	
		$sqlDimen = "CREATE TABLE tt_".trim($this->_getParam('team'))."_task(<br>";
		foreach ($taskDimension as $k => $v) {
			$sqlDimen .= $k . " " . $v[0] . " " . $v[3] ."<br>";
		}
		$sqlDimen .= "PRIMARY KEY id <br>)";
		$this->view->sqlDimen = $sqlDimen;
		$this->view->taskDimensions = $taskDimension;
		$this->view->teamId = $this->_getParam('team');
		if(count($this->view->errors)>0){
			$this->view->newFieldName = $_POST['newFieldName'];
			$this->view->newFieldDesc = $_POST['newFieldDesc'];
		}
	}
}